package web.java.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class VerifyLoginFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		System.out.println("进入拦截器。。");
		//排除掉不需要的连接
		HttpServletRequest request=(HttpServletRequest) req;
		HttpServletResponse response=(HttpServletResponse) res;
		String uri=request.getRequestURI();
		//切割字符串
		String[] str=uri.split("/");
		String action=str[str.length-1];
		if("LoginServlet".equals(action) || "login.jsp".equals(action)){
			chain.doFilter(req,res);
			return;
		}
		//获取session
		HttpSession session=request.getSession(false);
		if(session==null){
			//跳转到登录界面
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return;
		}else{
			boolean result=(Boolean)session.getAttribute("login");
			if(result){
				chain.doFilter(request,response);
				return;
			}else{
				//跳转到登录界面
				response.sendRedirect(request.getContextPath()+"/login.jsp");
				return;
			}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
